package cn.edu.sdjzu.xg23.kcsj01_backend.exception;


import cn.edu.sdjzu.xg23.kcsj01_backend.utils.Result;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.ResultCodeEnum;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    // 处理业务异常
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        return Result.error(e.getCode(), e.getMessage());
    }

    // 处理认证异常（包括JwtAuthenticationException）
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException e) {
        // 直接返回认证失败，无需区分具体原因（前端统一处理）
        return Result.error(ResultCodeEnum.TOKEN_CHECK_ERROR);
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String errorMsg = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.error(ResultCodeEnum.PARAM_ERROR.code, errorMsg);
    }
    // 处理权限不足异常
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public Result handleAccessDeniedException(AccessDeniedException ex) {
        return Result.error(ResultCodeEnum.PERMISSION_DENIED);
    }
    // 兜底处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    public Result handleGlobalException(Exception e) {
        e.printStackTrace();
        return Result.error(ResultCodeEnum.SYSTEM_ERROR);
    }
}